<template>
  <div class="backups-page">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>备份记录</span>
          <el-space>
            <el-select v-model="filterDevice" placeholder="筛选设备" clearable @change="loadBackups">
              <el-option
                v-for="device in devices"
                :key="device.id"
                :label="device.name"
                :value="device.id"
              />
            </el-select>
          </el-space>
        </div>
      </template>

      <el-table :data="backups" v-loading="loading" stripe>
        <el-table-column label="设备名称" width="150">
          <template #default="{ row }">
            {{ row.device?.name }}
          </template>
        </el-table-column>
        <el-table-column prop="filename" label="文件名" width="250" />
        <el-table-column label="文件大小" width="120">
          <template #default="{ row }">
            {{ formatSize(row.file_size) }}
          </template>
        </el-table-column>
        <el-table-column label="备份时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.backup_time) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="row.is_manual ? 'warning' : 'info'" size="small">
              {{ row.is_manual ? '手动' : '自动' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="错误信息" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.error_message || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="200">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="viewContent(row)">查看</el-button>
            <el-button type="warning" size="small" @click="selectForCompare(row)" :disabled="row.status !== 'success'">
              对比
            </el-button>
            <el-popconfirm title="确定删除这个备份吗？" @confirm="deleteBackup(row)">
              <template #reference>
                <el-button type="danger" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 查看配置对话框 -->
    <el-dialog v-model="contentDialogVisible" title="配置内容" width="80%">
      <el-input
        v-model="configContent"
        type="textarea"
        :rows="20"
        readonly
        style="font-family: monospace;"
      />
    </el-dialog>

    <!-- 配置对比对话框 -->
    <el-dialog v-model="compareDialogVisible" title="配置对比" width="90%">
      <div v-if="!compareBackup1">
        <el-alert title="请选择第一个备份进行对比" type="info" :closable="false" />
      </div>
      <div v-else-if="!compareBackup2">
        <el-alert :title="`已选择: ${compareBackup1.filename}，请选择第二个备份`" type="success" :closable="false" />
      </div>
      <div v-else>
        <el-descriptions :column="2" border style="margin-bottom: 20px;">
          <el-descriptions-item label="备份1">{{ compareBackup1.filename }}</el-descriptions-item>
          <el-descriptions-item label="备份2">{{ compareBackup2.filename }}</el-descriptions-item>
        </el-descriptions>
        <el-button type="primary" @click="performCompare" :loading="comparing">开始对比</el-button>
        <el-button @click="resetCompare">重置</el-button>
        
        <div v-if="diffResult" style="margin-top: 20px;">
          <el-alert v-if="!diffResult.has_changes" title="配置无变化" type="success" />
          <el-input
            v-else
            v-model="diffResult.diff"
            type="textarea"
            :rows="25"
            readonly
            style="font-family: monospace; margin-top: 10px;"
          />
        </div>
      </div>
      <template #footer>
        <el-button @click="compareDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { backupApi, deviceApi } from '@/api'
import { ElMessage } from 'element-plus'

const loading = ref(false)
const backups = ref([])
const devices = ref([])
const filterDevice = ref(null)
const contentDialogVisible = ref(false)
const configContent = ref('')
const compareDialogVisible = ref(false)
const compareBackup1 = ref(null)
const compareBackup2 = ref(null)
const comparing = ref(false)
const diffResult = ref(null)

const loadBackups = async () => {
  loading.value = true
  try {
    const params = filterDevice.value ? { device_id: filterDevice.value } : {}
    backups.value = await backupApi.getBackups(params)
  } catch (error) {
    ElMessage.error('加载备份列表失败')
  } finally {
    loading.value = false
  }
}

const loadDevices = async () => {
  try {
    devices.value = await deviceApi.getDevices()
  } catch (error) {
    console.error('加载设备列表失败')
  }
}

const formatSize = (bytes) => {
  if (bytes < 1024) return bytes + ' B'
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + ' KB'
  return (bytes / 1024 / 1024).toFixed(2) + ' MB'
}

const formatTime = (time) => {
  return new Date(time).toLocaleString('zh-CN')
}

const getStatusType = (status) => {
  return status === 'success' ? 'success' : status === 'failed' ? 'danger' : 'warning'
}

const getStatusText = (status) => {
  const map = { success: '成功', failed: '失败', in_progress: '进行中' }
  return map[status] || status
}

const viewContent = async (row) => {
  try {
    const result = await backupApi.getBackupContent(row.id)
    configContent.value = result.content
    contentDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取配置内容失败')
  }
}

const selectForCompare = (row) => {
  if (!compareBackup1.value) {
    compareBackup1.value = row
    ElMessage.success('已选择第一个备份，请选择第二个备份')
    compareDialogVisible.value = true
  } else if (!compareBackup2.value) {
    compareBackup2.value = row
    ElMessage.success('已选择第二个备份，可以开始对比')
  } else {
    ElMessage.warning('请先重置对比')
  }
}

const resetCompare = () => {
  compareBackup1.value = null
  compareBackup2.value = null
  diffResult.value = null
}

const performCompare = async () => {
  comparing.value = true
  try {
    diffResult.value = await backupApi.compareBackups(
      compareBackup1.value.id,
      compareBackup2.value.id
    )
  } catch (error) {
    ElMessage.error('配置对比失败')
  } finally {
    comparing.value = false
  }
}

const deleteBackup = async (row) => {
  try {
    await backupApi.deleteBackup(row.id)
    ElMessage.success('备份已删除')
    loadBackups()
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

onMounted(() => {
  loadBackups()
  loadDevices()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 500;
}
</style>

